<?php
class Router
{
	private $rules;
	private $urlforIndexs;
	public function __construct() {
		$this->rules = array();
		$this->urlforIndexs = array();
	}
	public function addRule($rule) {
		$this->rules[] = $rule;
	}
	public function compile() {
		foreach ($this->rules as $rule) {
			$rule->compile();
		}
		$this->buildUrlForIndexs();
	}
	public function dispatch($context, $url) {
		foreach ($this->rules as $rule) {
			if ($rule->dispatch($context, $url))
				return true;
		}
		throw new RouterException("Rule : Cann't dispatch $url");
	}
	public function urlfor($controller, $params = array(), $oCharset = 'gbk', $iCharset = 'gbk') {
		$controller = strtolower($controller);
		if (isset($this->urlforIndexs[$controller])) {
			$rule = $this->urlforIndexs[$controller];
		} else {
			$rule = $this->urlforIndexs['*'];
		}
		return $rule->urlfor($controller, $params, $oCharset, $iCharset);
	}
	private function buildUrlForIndexs() {
		foreach ($this->rules as $rule) {
			$this->urlforIndexs[$rule->getIndex()] = $rule;
		}
	}
}
?>
